export default class JArr {
    constructor() {
        //@ts-ignore
        Array.prototype.unique = this._unique;
        //@ts-ignore
        Array.prototype.inline = this._inline;
        //@ts-ignore
        Array.prototype.finds = this._finds;
        //@ts-ignore
        Array.prototype.translate = this._translate;
    }
    _translate = function (config: any = {}) {
        //@ts-ignore
        if (Array.isArray(this)) {
            //@ts-ignore
            const self = [...this];
            const result: any[] = [];
            self.map((item: any) => {
                const temp: any = {...item};
                Object.keys(config).map((key) => {
                    temp[config[key]] = temp[key];
                    delete temp[key];
                });
                result.push(temp);
            });
            return result;
        }
    };
    //去重 unique
    _unique = function () {
        //@ts-ignore
        if (Array.isArray(this)) {
            //@ts-ignore
            const self = [...this];
            //@ts-ignore
            return [...new Set(self)];
        }
    };
    //扁平化 inline
    _inline = function (key: string) {
        //@ts-ignore
        if (Array.isArray(this)) {
            const getFlatTreeData = (treeData: any[], result?: any[]) => {
                const treeResult = result || [];
                treeData.map((item: any) => {
                    treeResult.push(item);
                    if (Array.isArray(item[key]) && item.children.length > 0) {
                        getFlatTreeData(item[key], treeResult);
                    }
                });
                return treeResult || [];
            };
            //@ts-ignore
            const self = [...this];
            return getFlatTreeData(self);
        }
    };
    //finds //包含
    _finds = function (key: string, value?: string | number) {
        //@ts-ignore
        if (Array.isArray(this)) {
            //@ts-ignore
            const self = [...this];
            let index = -1;
            let result;
            if (value || value === 0) {
                self.map((item, idx) => {
                    if (item[key] === value) {
                        result = {...item};
                        index = idx;
                    }
                });
            } else {
                self.map((item, idx) => {
                    if (item === key) {
                        result = key;
                        index = idx;
                    }
                });
            }
            return {
                result,
                index
            };
        }
    };
}
